﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConcatSQLText
{
    class Program
    {
        const int COMMENTLEN = 150;
        static void Main(string[] args)
        {

            if (args.Length < 2)
            {
                Console.WriteLine("Too few arguments.");
                Console.WriteLine("Usage: ConcatSQLText <file pattern> <output file>");
                return;
            }

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(args[0]));
            string[] pts = args[0].Split(new char[] { Path.DirectorySeparatorChar });

            FileInfo fiOut = new FileInfo(args[1]);
            if (fiOut.Exists)
                fiOut.Delete();

            FileInfo[] fis = di.GetFiles(pts[pts.Length - 1]);
            var filesOrdered = fis.OrderBy(item => item.Name);


            foreach (FileInfo fi in filesOrdered)
            {
                Console.WriteLine("Adding file {0:S}", fi.FullName);

                using (StreamWriter sw = new StreamWriter(new FileStream(
                        fiOut.FullName, FileMode.Append, FileAccess.Write, FileShare.Read)))
                {
                    sw.WriteLine(WriteDashes(COMMENTLEN));
                    sw.WriteLine(WriteDashes(COMMENTLEN));
                    sw.WriteLine(WriteCenter(fi.Name, COMMENTLEN));
                    //sw.WriteLine(WriteDashes(COMMENTLEN));
                    //sw.WriteLine(WriteCenter(string.Format("Content merged from {0:S} at {1:S}", fi.Name, DateTime.Now.ToString()), COMMENTLEN));
                    sw.WriteLine(WriteDashes(COMMENTLEN));
                    sw.WriteLine(WriteDashes(COMMENTLEN));

                    using (StreamReader sr = new StreamReader(new FileStream(
                        fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)))
                    {

                        sw.WriteLine(sr.ReadToEnd());
                    }
                }
            }
        }
        static string WriteDashes(int len)
        {
            StringBuilder sb = new StringBuilder(len);
            for (int i = 0; i < len; i++)
                sb.Append("-");

            return sb.ToString();
        }

        static string WriteCenter(string str, int len)
        {
            int iStart = (len - (str.Length + 2)) / 2;
            StringBuilder sb = new StringBuilder(len);
            for (int i = 0; i < iStart; i++)
                sb.Append("-");
            sb.AppendFormat(" {0:S} ", str);
            for (int i = iStart + str.Length + 2; i < len; i++)
                sb.Append("-");

            return sb.ToString();
        }
    }
}
